<template>
  <div class="ai-assistant" :class="{ fullscreen: props.fullscreen }">
    <!-- 头部信息 -->
    <div class="ai-header">
      <div class="ai-title">
        <el-icon class="ai-icon"><ChatDotSquare /></el-icon>
        <span>智能学习助手</span>
        <el-tag v-if="courseId" type="success" size="small">课程专属</el-tag>
        <el-tag v-else type="info" size="small">全局助手</el-tag>
      </div>
      <div class="ai-status">
        <el-badge :value="documents.length" class="docs-badge">
          <el-button 
            size="small" 
            type="primary" 
            @click="showKnowledgeBase = !showKnowledgeBase"
          >
            <el-icon v-if="!showKnowledgeBase"><Document /></el-icon>
            <el-icon v-else><Hide /></el-icon>
            知识库
          </el-button>
        </el-badge>
      </div>
    </div>

    <!-- 知识库管理区域 -->
    <el-collapse-transition>
      <div v-show="showKnowledgeBase" class="knowledge-base">
        <div class="kb-header">
          <h4>📚 知识库管理</h4>
          <div class="kb-actions">
            <el-button 
              type="primary" 
              size="small" 
              @click="triggerFileUpload"
              :loading="uploading"
            >
              <el-icon v-if="!uploading"><Upload /></el-icon>
              <el-icon v-else><Loading /></el-icon>
              {{ uploading ? '上传中...' : '上传文档' }}
            </el-button>
            <el-button 
              size="small" 
              @click="loadDocuments"
              :loading="loadingDocs"
            >
              <el-icon v-if="!loadingDocs"><Refresh /></el-icon>
              <el-icon v-else><Loading /></el-icon>
              刷新
            </el-button>
          </div>
        </div>

        <!-- 文件上传 -->
        <input 
          ref="fileInput" 
          type="file" 
          multiple 
          accept=".pdf,.txt,.docx,.doc,.md,.json,.csv" 
          @change="uploadFiles" 
          style="display: none"
        />

        <!-- 文档列表 -->
        <div class="documents-list">
          <div v-if="documents.length === 0" class="empty-docs">
            <el-empty description="暂无文档，点击上传按钮添加文档">
              <el-button type="primary" @click="triggerFileUpload">立即上传</el-button>
            </el-empty>
          </div>
          <div v-else class="docs-grid">
            <div 
              v-for="doc in documents" 
              :key="doc.id" 
              class="doc-card"
              :class="{ 'selected': selectedDocIds.includes(doc.id) }"
              @click="toggleDocSelection(doc.id)"
            >
              <div class="doc-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="doc-info">
                <div class="doc-name" :title="doc.filename">{{ doc.filename }}</div>
                <div class="doc-meta">
                  <span class="chunks">{{ doc.chunk_count }} 片段</span>
                  <span class="size">{{ formatFileSize(doc.file_size) }}</span>
                </div>
              </div>
              <div class="doc-actions">
                <el-icon v-if="selectedDocIds.includes(doc.id)" class="check-icon"><Check /></el-icon>
                <el-button 
                  size="small" 
                  type="danger" 
                  :icon="Delete"
                  @click.stop="deleteDocument(doc)"
                  class="delete-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 文档选择提示 -->
        <div v-if="selectedDocIds.length > 0" class="selection-info">
          <el-alert 
            :title="`已选择 ${selectedDocIds.length} 个文档，AI将基于这些文档回答问题`"
            type="info" 
            show-icon 
            :closable="false"
          >
            <template #default>
              <el-button size="small" type="text" @click="clearSelection">清除选择</el-button>
            </template>
          </el-alert>
        </div>
      </div>
    </el-collapse-transition>

    <!-- 聊天区域 -->
    <div class="chat-container">
      <!-- 设置栏 -->
      <div class="settings-bar">
        <el-switch v-model="useAI" active-text="AI模式" inactive-text="规则模式" />
        <div class="kv">
          <span>TopK</span>
          <el-input-number v-model="topK" :min="1" :max="20" size="small" />
        </div>
      </div>
      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-message">
          <div class="welcome-content">
            <el-icon class="welcome-icon"><ChatLineSquare /></el-icon>
            <h3>👋 欢迎使用智能学习助手</h3>
            <p>我可以帮助您：</p>
            <ul class="features-list">
              <li>📖 基于上传文档进行问答</li>
              <li>💡 提供学习建议和解答疑问</li>
              <li>✍️ 协助写作和内容创作</li>
              <li>🧠 智能分析和总结</li>
            </ul>
            <p class="tip">💡 上传相关文档后，我的回答会更加准确专业！</p>
          </div>
        </div>

        <div v-for="(message, index) in messages" :key="index" class="message" :class="message.type">
          <div class="message-avatar">
            <el-avatar v-if="message.type === 'user'" :size="36">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="36" class="ai-avatar">
              <el-icon><Avatar /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="sender">{{ message.type === 'user' ? '我' : 'AI助手' }}</span>
              <span class="time">{{ formatTime(message.timestamp) }}</span>
            </div>
            <div class="message-text">
              <div v-if="message.type === 'user'" class="user-message">
                {{ message.content }}
              </div>
              <div v-else class="ai-message">
                <div v-html="renderMarkdown(message.content)" class="markdown-content"></div>
                <div v-if="message.sources && message.sources.length > 0" class="sources">
                  <el-divider content-position="left">参考来源</el-divider>
                  <div class="source-list">
                    <el-tag
                      v-for="src in message.sources"
                      :key="typeof src === 'string' ? src : (src.doc_id || src.filename)"
                      size="small"
                      type="info"
                      class="source-tag"
                      @click="reaskWithSource(src)"
                    >
                      <template v-if="typeof src === 'string'">📄 {{ src }}</template>
                      <template v-else>📄 {{ src.filename }} <span v-if="src.score != null">({{ formatScore(src.score) }})</span></template>
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载动画 -->
        <div v-if="isLoading" class="message ai">
          <div class="message-avatar">
            <el-avatar :size="36" class="ai-avatar">
              <el-icon><Avatar /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="loading-animation">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>正在思考中...</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-container">
        <div class="input-wrapper">
          <el-input
            v-model="currentMessage"
            placeholder="请输入您的问题..."
            @keydown.enter="sendMessage"
            :disabled="isLoading"
            class="message-input"
            size="large"
            clearable
          >
            <template #prepend>
              <el-icon><Edit /></el-icon>
            </template>
            <template #append>
              <el-button 
                type="primary" 
                @click="sendMessage" 
                :disabled="!currentMessage.trim() || isLoading"
                :loading="isLoading"
              >
                <el-icon v-if="!isLoading">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <line x1="22" y1="2" x2="11" y2="13"></line>
                    <polygon points="22,2 15,22 11,13 2,9"></polygon>
                  </svg>
                </el-icon>
                发送
              </el-button>
            </template>
          </el-input>
        </div>
        
        <!-- 快速操作 -->
        <div class="quick-actions">
          <el-button-group size="small">
            <el-button @click="insertQuickText('请总结一下文档的主要内容')">📝 总结文档</el-button>
            <el-button @click="insertQuickText('请解释一下')">💡 详细解释</el-button>
            <el-button @click="insertQuickText('请举个例子')">🌰 举例说明</el-button>
            <el-button @click="clearChat">🗑️ 清空对话</el-button>
          </el-button-group>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { aiApi, type DocumentInfo } from '@/api/ai'
import { getErrorMessage } from '@/api/http'
import MarkdownIt from 'markdown-it'
import markdownItKatex from 'markdown-it-katex'
import hljs from 'highlight.js'
import 'katex/dist/katex.min.css'
import 'highlight.js/styles/github.css'
import { 
  ChatDotSquare, 
  Document, 
  Upload, 
  Refresh, 
  Check, 
  User, 
  Avatar,
  Edit,
  Loading,
  ChatLineSquare,
  Hide,
  Delete
} from '@element-plus/icons-vue'

// Props
interface Props {
  userId: number
  courseId?: number
  fullscreen?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  userId: 0,
  courseId: undefined,
  fullscreen: false
})

// 状态管理
const showKnowledgeBase = ref(false)
const documents = ref<DocumentInfo[]>([])
const selectedDocIds = ref<string[]>([])
type SourceRef = string | { filename: string; doc_id?: string; score?: number; index?: number; preview?: string }
const messages = ref<Array<{
  type: 'user' | 'ai'
  content: string
  timestamp: Date
  sources?: SourceRef[]
}>>([])
const currentMessage = ref('')
const isLoading = ref(false)
const uploading = ref(false)
const loadingDocs = ref(false)
const useAI = ref(true)
const topK = ref(4)

// DOM引用
const fileInput = ref<HTMLInputElement>()
const messagesContainer = ref<HTMLElement>()

// Markdown 渲染（支持 KaTeX 数学公式与代码高亮）
const md = new MarkdownIt({
  html: false,
  linkify: true,
  typographer: true,
  breaks: true,
  highlight: (code: string, lang?: string) => {
    try {
      if (lang && hljs.getLanguage(lang)) {
        return '<pre class="hljs"><code>' +
          hljs.highlight(code, { language: lang, ignoreIllegals: true }).value +
          '</code></pre>'
      }
      return '<pre class="hljs"><code>' + hljs.highlightAuto(code).value + '</code></pre>'
    } catch {
      const escape = (s: string) => s.replace(/[&<>"']/g, (ch) => ({
        '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
      }[ch] as string))
      return '<pre class="hljs"><code>' + escape(code) + '</code></pre>'
    }
  }
}).use(markdownItKatex, {
  strict: false,
  throwOnError: false,
  errorColor: '#cc0000',
  displayMode: false,
  macros: {
    "\\RR": "\\mathbb{R}",
    "\\CC": "\\mathbb{C}",
    "\\NN": "\\mathbb{N}",
    "\\ZZ": "\\mathbb{Z}",
    "\\QQ": "\\mathbb{Q}",
    "\\argmax": "\\operatorname{argmax}",
    "\\argmin": "\\operatorname{argmin}",
    "\\max": "\\operatorname{max}",
    "\\min": "\\operatorname{min}"
  }
})

const renderMarkdown = (content: string) => {
  // 预处理内容，确保数学公式正确识别
  let processedContent = content
  
  // 处理行内数学公式 - 保持 $...$ 格式用于行内显示
  
  // 处理块级数学公式 - 确保独立行显示
  processedContent = processedContent.replace(/\$\$([^$]+?)\$\$/g, (match, formula) => {
    return '\n$$' + formula.trim() + '$$\n'
  })
  
  // 处理 LaTeX 环境（如 \begin{align}...\end{align}）
  processedContent = processedContent.replace(/(\\begin\{[^}]+\}[\s\S]*?\\end\{[^}]+\})/g, (match) => {
    return '\n$$' + match + '$$\n'
  })
  
  // 处理常见的数学符号，确保它们在 LaTeX 中正确显示
  const mathReplacements = {
    '≤': '\\leq',
    '≥': '\\geq', 
    '≠': '\\neq',
    '±': '\\pm',
    '∞': '\\infty',
    '∑': '\\sum',
    '∏': '\\prod',
    '∫': '\\int',
    '∂': '\\partial',
    '∇': '\\nabla',
    '∆': '\\Delta',
    'α': '\\alpha',
    'β': '\\beta',
    'γ': '\\gamma',
    'δ': '\\delta',
    'ε': '\\varepsilon',
    'θ': '\\theta',
    'λ': '\\lambda',
    'μ': '\\mu',
    'π': '\\pi',
    'σ': '\\sigma',
    'φ': '\\varphi',
    'ω': '\\omega',
    '→': '\\rightarrow',
    '←': '\\leftarrow',
    '↔': '\\leftrightarrow',
    '⇒': '\\Rightarrow',
    '⇐': '\\Leftarrow',
    '⇔': '\\Leftrightarrow',
    '∀': '\\forall',
    '∃': '\\exists',
    '∈': '\\in',
    '∉': '\\notin',
    '⊂': '\\subset',
    '⊃': '\\supset',
    '⊆': '\\subseteq',
    '⊇': '\\supseteq',
    '∪': '\\cup',
    '∩': '\\cap',
    '∅': '\\emptyset',
    '×': '\\times',
    '÷': '\\div',
    '·': '\\cdot',
    '√': '\\sqrt'
  }
  
  // 在数学环境中替换这些符号（块级公式）
  processedContent = processedContent.replace(/\$\$([^$]+?)\$\$/g, (match, formula) => {
    let processedFormula = formula
    Object.entries(mathReplacements).forEach(([unicode, latex]) => {
      processedFormula = processedFormula.replace(new RegExp(unicode, 'g'), latex)
    })
    return '$$' + processedFormula + '$$'
  })
  
  // 在数学环境中替换这些符号（行内公式）
  processedContent = processedContent.replace(/\$([^$\n]+?)\$/g, (match, formula) => {
    let processedFormula = formula
    Object.entries(mathReplacements).forEach(([unicode, latex]) => {
      processedFormula = processedFormula.replace(new RegExp(unicode, 'g'), latex)
    })
    return '$' + processedFormula + '$'
  })
  
  // 处理常见的数学表达式格式
  // 处理分数：将 (a)/(b) 转换为 \frac{a}{b}
  processedContent = processedContent.replace(/\$([^$]*)\(([^)]+)\)\/\(([^)]+)\)([^$]*)\$/g, '$$$1\\frac{$2}{$3}$4$$')
  
  // 处理指数：将 x^(a+b) 格式优化
  processedContent = processedContent.replace(/\$([^$]*\w)\^(\([^)]+\))([^$]*)\$/g, '$$$1^{$2}$3$$')
  
  // 处理下标：将 x_(i+j) 格式优化
  processedContent = processedContent.replace(/\$([^$]*\w)_(\([^)]+\))([^$]*)\$/g, '$$$1_{$2}$3$$')
  
  return md.render(processedContent)
}

const formatScore = (s: any) => {
  if (s == null || isNaN(s)) return ''
  try { return Number(s).toFixed(3) } catch { return String(s) }
}

const reaskWithSource = async (src: any) => {
  const docId = typeof src === 'string' ? null : (src.doc_id || null)
  if (!docId) return
  selectedDocIds.value = [docId]
  if (!currentMessage.value.trim()) {
    currentMessage.value = '基于该文档继续回答'
  }
  await sendMessage()
}

// 方法
const loadDocuments = async () => {
  loadingDocs.value = true
  try {
    const response = await aiApi.listDocs(props.userId, props.courseId)
    documents.value = response.data?.documents || []
    console.log('📚 加载文档列表:', documents.value.length, '个文档')
  } catch (error: any) {
    console.error('加载文档失败:', error)
    ElMessage.error(getErrorMessage(error))
  } finally {
    loadingDocs.value = false
  }
}

const triggerFileUpload = () => {
  fileInput.value?.click()
}

const uploadFiles = async (event: Event) => {
  const files = (event.target as HTMLInputElement).files
  if (!files || files.length === 0) return

  uploading.value = true
  try {
    for (const file of Array.from(files)) {
      console.log('📤 上传文件:', file.name)
      await aiApi.uploadDoc(file, props.userId?.toString(), props.courseId?.toString())
      ElMessage.success(`文件 ${file.name} 上传成功`)
    }
    
    // 重置文件输入
    if (fileInput.value) {
      fileInput.value.value = ''
    }
    
    // 延迟加载文档列表，给后端处理时间
    setTimeout(() => {
      loadDocuments()
    }, 1500)
    
  } catch (error: any) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败: ' + getErrorMessage(error))
  } finally {
    uploading.value = false
  }
}

const toggleDocSelection = (docId: string) => {
  const index = selectedDocIds.value.indexOf(docId)
  if (index === -1) {
    selectedDocIds.value.push(docId)
  } else {
    selectedDocIds.value.splice(index, 1)
  }
}

const clearSelection = () => {
  selectedDocIds.value = []
}

const deleteDocument = async (doc: DocumentInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档 "${doc.filename}" 吗？此操作不可撤销。`, 
      '确认删除', 
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    await aiApi.deleteDoc(doc.id, props.userId, props.courseId)
    ElMessage.success(`文档 ${doc.filename} 删除成功`)
    
    // 从选中列表中移除
    const index = selectedDocIds.value.indexOf(doc.id)
    if (index > -1) {
      selectedDocIds.value.splice(index, 1)
    }
    
    // 刷新文档列表
    await loadDocuments()
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除文档失败:', error)
      ElMessage.error('删除失败: ' + getErrorMessage(error))
    }
  }
}

const sendMessage = async () => {
  if (!currentMessage.value.trim() || isLoading.value) return

  const userMessage = currentMessage.value.trim()
  currentMessage.value = ''

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: userMessage,
    timestamp: new Date()
  })

  // 滚动到底部
  await scrollToBottom()

  isLoading.value = true
  try {
    const { data } = await aiApi.ask({
      question: userMessage,
      userId: props.userId,
      courseId: props.courseId,
      docIds: selectedDocIds.value.length > 0 ? selectedDocIds.value : undefined,
      useAI: useAI.value,
      topK: topK.value
    })

    // 添加AI回复（保留后端结构，模板中已兼容string或对象）
    const sources: SourceRef[] = (data?.source_docs || data?.sources || []) as SourceRef[]

    messages.value.push({
      type: 'ai',
      content: data?.answer || '抱歉，我无法回答您的问题。',
      timestamp: new Date(),
      sources
    })

    await scrollToBottom()
  } catch (error: any) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败: ' + getErrorMessage(error))
    
    // 添加错误消息
    messages.value.push({
      type: 'ai',
      content: '抱歉，我暂时无法回答您的问题，请稍后再试。',
      timestamp: new Date()
    })
  } finally {
    isLoading.value = false
    await scrollToBottom()
  }
}

const insertQuickText = (text: string) => {
  currentMessage.value = text
}

const clearChat = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有对话记录吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    messages.value = []
  } catch {
    // 用户取消
  }
}

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const formatFileSize = (bytes: number) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// renderMarkdown已在上面定义

// 生命周期
onMounted(() => {
  loadDocuments()
})
</script>

<style scoped>
.ai-assistant {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
  border-radius: 12px;
  overflow: hidden;
}

.ai-assistant.fullscreen {
  position: static;
  width: 100%;
  max-height: none;
  height: 80vh;
  margin: 20px 0;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e5e7eb;
}

.ai-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
}

.ai-icon {
  font-size: 20px;
}

.ai-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.docs-badge :deep(.el-badge__content) {
  background: #67c23a;
}

.knowledge-base {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 20px;
}

.kb-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.kb-header h4 {
  margin: 0;
  color: #303133;
  font-size: 14px;
}

.kb-actions {
  display: flex;
  gap: 8px;
}

.documents-list {
  margin-top: 12px;
}

.empty-docs {
  text-align: center;
  padding: 20px;
}

.docs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.doc-card {
  background: #f8f9fa;
  border: 2px solid transparent;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
}

.doc-card:hover {
  background: #e3f2fd;
  border-color: #2196f3;
}

.doc-card.selected {
  background: #e8f5e8;
  border-color: #4caf50;
}

.doc-icon {
  color: #606266;
  font-size: 20px;
  flex-shrink: 0;
}

.doc-info {
  flex: 1;
  min-width: 0;
}

.doc-name {
  font-weight: 500;
  font-size: 13px;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.doc-meta {
  display: flex;
  gap: 8px;
  font-size: 11px;
  color: #909399;
}

.doc-actions {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.check-icon {
  color: #67c23a;
  font-size: 16px;
}

.delete-btn {
  padding: 4px 8px;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.doc-card:hover .delete-btn {
  opacity: 1;
}

.selection-info {
  margin-top: 12px;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.settings-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 20px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.settings-bar .kv {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
  color: #606266;
}

.welcome-content {
  max-width: 400px;
  margin: 0 auto;
}

.welcome-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 16px;
}

.welcome-content h3 {
  margin: 16px 0;
  color: #303133;
  font-size: 18px;
}

.features-list {
  text-align: left;
  margin: 16px 0;
  padding-left: 20px;
}

.features-list li {
  margin: 8px 0;
  font-size: 14px;
}

.tip {
  font-size: 13px;
  color: #909399;
  font-style: italic;
  margin-top: 16px;
}

.message {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.ai-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message.user .message-content {
  text-align: right;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 12px;
  color: #909399;
}

.message.user .message-header {
  flex-direction: row-reverse;
}

.sender {
  font-weight: 500;
}

.message-text {
  max-width: 80%;
}

.message.user .message-text {
  margin-left: auto;
}

.user-message {
  background: #409eff;
  color: white;
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
}

.ai-message {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 16px;
  line-height: 1.6;
}

.markdown-content {
  color: #303133;
  font-size: 14px;
  line-height: 1.6;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
  margin: 16px 0 8px 0;
  color: #303133;
}

.markdown-content :deep(p) {
  margin: 12px 0;
  text-align: justify;
}

/* 列表样式优化 */
.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  margin: 12px 0;
  padding-left: 24px;
}

.markdown-content :deep(li) {
  margin: 6px 0;
  line-height: 1.5;
}

/* 引用块样式 */
.markdown-content :deep(blockquote) {
  margin: 16px 0;
  padding: 12px 16px;
  border-left: 4px solid #409eff;
  background: #f8f9fa;
  border-radius: 0 4px 4px 0;
  font-style: italic;
}

/* 表格样式优化 */
.markdown-content :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  font-size: 13px;
}

.markdown-content :deep(th),
.markdown-content :deep(td) {
  border: 1px solid #e1e4e8;
  padding: 8px 12px;
  text-align: left;
}

.markdown-content :deep(th) {
  background: #f6f8fa;
  font-weight: 600;
}

/* 强调文本样式 */
.markdown-content :deep(strong) {
  color: #303133;
  font-weight: 600;
}

.markdown-content :deep(em) {
  color: #606266;
  font-style: italic;
}

.markdown-content :deep(code) {
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
}

.markdown-content :deep(pre) {
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  overflow-x: auto;
  margin: 12px 0;
}

/* KaTeX 数学公式样式优化 */
.markdown-content :deep(.katex) {
  font-size: 1.1em;
  color: #303133;
}

.markdown-content :deep(.katex-display) {
  margin: 16px 0;
  padding: 12px;
  background: #fafafa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  overflow-x: auto;
  text-align: center;
}

.markdown-content :deep(.katex-display > .katex) {
  text-align: center;
  white-space: nowrap;
}

/* 行内公式样式 */
.markdown-content :deep(.katex:not(.katex-display)) {
  background: #f5f7fa;
  padding: 2px 4px;
  border-radius: 3px;
  margin: 0 2px;
}

/* 修复数学符号的字体渲染 */
.markdown-content :deep(.katex .mathnormal) {
  font-family: KaTeX_Math, Times, serif;
}

.markdown-content :deep(.katex .mathit) {
  font-family: KaTeX_Math, Times, serif;
  font-style: italic;
}

/* 优化分数和上下标的显示 */
.markdown-content :deep(.katex .frac-line) {
  border-bottom-width: 0.04em;
}

.markdown-content :deep(.katex .mord + .mord) {
  margin-left: 0;
}

/* 优化特殊数学符号 */
.markdown-content :deep(.katex .mop) {
  font-family: KaTeX_Main, Times, serif;
}

.markdown-content :deep(.katex .mbin) {
  margin: 0 0.2777777778em;
}

.markdown-content :deep(.katex .mrel) {
  margin: 0 0.2777777778em;
}

/* 优化长公式的换行和滚动 */
.markdown-content :deep(.katex-display) {
  max-width: 100%;
  overflow-x: auto;
}

.markdown-content :deep(.katex-display .katex) {
  min-width: max-content;
}

/* 改善求和、积分等大符号的显示 */
.markdown-content :deep(.katex .mop.op-limits) {
  text-align: center;
}

/* 优化矩阵和分数的对齐 */
.markdown-content :deep(.katex .arraycolsep) {
  width: 0.5em;
}

/* 改善上下标的位置 */
.markdown-content :deep(.katex .supsub) {
  text-align: left;
}

/* 数学文本的行高优化 */
.markdown-content :deep(.katex) {
  line-height: 1.2;
}

.markdown-content :deep(.katex-display .katex) {
  line-height: 1.4;
}

/* 改善嵌套公式的间距 */
.markdown-content :deep(.katex .nulldelimiter) {
  width: 0;
}

/* 优化括号匹配 */
.markdown-content :deep(.katex .delimsizing) {
  font-family: KaTeX_Size1, KaTeX_Main, Times, serif;
}

/* 数学模式下的文字间距 */
.markdown-content :deep(.katex .mathdefault) {
  font-family: KaTeX_Math, Times, serif;
  font-style: italic;
}

/* 改善数学符号的抗锯齿 */
.markdown-content :deep(.katex) {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.sources {
  margin-top: 16px;
  padding-top: 12px;
}

.source-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.source-tag {
  font-size: 11px;
}

.loading-animation {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-style: italic;
}

.input-container {
  background: white;
  border-top: 1px solid #e4e7ed;
  padding: 16px 20px;
}

.input-wrapper {
  margin-bottom: 12px;
}

.message-input {
  font-size: 14px;
}

.quick-actions {
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .docs-grid {
    grid-template-columns: 1fr;
  }
  
  .message-text {
    max-width: 90%;
  }
  
  .kb-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .quick-actions {
    overflow-x: auto;
    justify-content: flex-start;
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>